import os
import logging

# 配置日志级别，关闭Langfuse的debug日志
logging.getLogger("langfuse").setLevel(logging.WARNING)
logging.getLogger("langfuse._task_manager.media_manager").setLevel(logging.WARNING)
logging.getLogger("langfuse._task_manager").setLevel(logging.WARNING)
logging.getLogger("langfuse._task_manager.task_manager").setLevel(logging.WARNING)

# 设置根日志级别为INFO，允许调试日志显示
logging.basicConfig(level=logging.INFO)

# 必须在导入任何其他模块之前设置环境变量
# 设置Langfuse环境变量 (2.x版本) - 禁用自动集成
os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-73b135d1-ac15-4da4-85c0-7e973ed7a516"
os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-60f3b528-5673-4e6d-afef-b49a0c6bccd0"
os.environ["LANGFUSE_HOST"] = "https://test.langfuse.cyouai.com"

# 禁用Langfuse的自动集成，因为使用的是方舟API
os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"

# 确保OpenAI不会尝试设置langfuse_public_key属性
os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
os.environ["OPENAI_LANGFUSE_HOST"] = ""

from contextlib import asynccontextmanager
from fastapi import FastAPI
from langserve import add_routes
from models.commit_message_model import CommitMessageModel
from api.routes import router as commit_router
from api.rag_routes import router as rag_router
from api.knowledge_base_routes import router as kb_router
from api.workflow_routes import router as workflow_router  # 新增工作流路由

from api.code_review_routes import router as code_review_router  # 新增代码审查路由
from config import Config
from monitoring.langfuse_manager import LangfuseManager  # 导入Langfuse管理器
import uvicorn

# 设置Langfuse的其他环境变量
os.environ["LANGFUSE_ENABLED"] = str(Config.LANGFUSE_ENABLED).lower()

# 初始化Langfuse监控管理器（确保在模型初始化之前完成）
langfuse_manager = LangfuseManager()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时的操作
    yield  # 等待关闭
    
    # 关闭时刷新Langfuse数据
    if langfuse_manager.is_enabled():
        langfuse_manager.flush()

# 创建FastAPI应用
app = FastAPI(
    title="CodeLintAI - 智能代码分析服务",
    version="1.0.0",
    description="基于LangServe的智能Commit Message汇总生成和RAG文档问答服务，支持LangGraph工作流",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 确保在模型初始化之前禁用所有Langfuse自动集成
import os
os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"
os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
os.environ["OPENAI_LANGFUSE_HOST"] = ""

# 延迟初始化模型
commit_model = None

def get_commit_model():
    """获取CommitMessageModel实例（延迟初始化）"""
    global commit_model
    if commit_model is None:
        # 确保在创建模型之前禁用Langfuse自动集成
        import os
        os.environ["LANGFUSE_OPENAI_INTEGRATION"] = "false"
        os.environ["LANGFUSE_AUTO_INSTRUMENT"] = "false"
        os.environ["OPENAI_LANGFUSE_PUBLIC_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_SECRET_KEY"] = ""
        os.environ["OPENAI_LANGFUSE_HOST"] = ""
        
        from models.commit_message_model import CommitMessageModel
        commit_model = CommitMessageModel()
    return commit_model

# 添加LangServe路由（提供playground功能）
add_routes(
    app,
    get_commit_model().chain,
    path="/langserve/commit"
)

# 添加Commit Message API路由
app.include_router(commit_router, prefix="/api", tags=["Commit Message"])

# 添加RAG API路由
app.include_router(rag_router, prefix="/api/rag", tags=["RAG"])

# 添加知识库管理API路由
app.include_router(kb_router, prefix="/api/kb", tags=["Knowledge Base"])

# 添加工作流API路由 - 新增
app.include_router(workflow_router, prefix="/api", tags=["LangGraph Workflow"])



# 添加代码审查API路由 - 新增
app.include_router(code_review_router, prefix="/api/code-review", tags=["Code Review"])

# 根路径
@app.get("/")
async def root():
    """服务信息"""
    return {
        "message": "CodeLintAI - 智能代码分析服务",
        "version": "1.0.0",
        "docs": "/docs",
        "playground": "/langserve/commit/playground",
        "apis": {
            "commit_summary": "/api/summarize",
            "rag_upload": "/api/rag/upload",
            "rag_ask": "/api/rag/ask",
            "rag_collections": "/api/rag/collections",
            "rag_collection_info": "/api/rag/collection/{name}",
            "rag_delete_collection": "/api/rag/collection/{name}",
            "rag_health": "/api/rag/health",
            "kb_create": "/api/kb/create",
            "kb_upload": "/api/kb/upload",
            "kb_smart_upload": "/api/kb/smart-upload",
            "kb_ask": "/api/kb/ask",
            "kb_list": "/api/kb/list",
            "kb_files": "/api/kb/{name}/files",
            "kb_delete_file": "/api/kb/{name}/files/{file}",
            "kb_delete": "/api/kb/{name}",
            "kb_info": "/api/kb/{name}/info",
            "kb_health": "/api/kb/health",
            # 新增工作流API
            "workflow_summarize": "/api/workflow/summarize",
            "workflow_rag_ask": "/api/workflow/rag/ask",
            "workflow_info": "/api/workflow/info",
            "workflow_trace_summarize": "/api/workflow/trace/summarize",
            "workflow_trace_rag": "/api/workflow/trace/rag",
            "workflow_health": "/api/workflow/health",

            # 代码审查API
            "code_review_check": "/api/code-review/check",
            "code_review_simple": "/api/code-review/check-simple",
            "code_review_extract_keywords": "/api/code-review/extract-keywords",
            "code_review_health": "/api/code-review/health"
        },
        "examples": {
            "list_kbs": "curl -X GET http://localhost:8000/api/kb/list",
            "create_kb": "curl -X POST http://localhost:8000/api/kb/create -H 'Content-Type: application/json' -d '{\"name\": \"测试库\", \"description\": \"测试用\"}'",
            "smart_upload": "curl -X POST http://localhost:8000/api/kb/smart-upload -F 'file=@document.pdf' -F 'knowledge_base_name=测试库'",
            "list_files": "curl -X GET http://localhost:8000/api/kb/测试库/files",
            "delete_file": "curl -X DELETE http://localhost:8000/api/kb/测试库/files/document.pdf",
            "delete_kb": "curl -X DELETE http://localhost:8000/api/kb/测试库",
            # 新增工作流示例
            "workflow_summarize": "curl -X POST http://localhost:8000/api/workflow/summarize -H 'Content-Type: application/json' -d '{\"summaries\": [{\"order\": 1, \"summary\": \"修复安全漏洞\"}]}'",
            "workflow_rag_ask": "curl -X POST http://localhost:8000/api/workflow/rag/ask -H 'Content-Type: application/json' -d '{\"question\": \"什么是代码审查？\"}'",
            "workflow_info": "curl -X GET http://localhost:8000/api/workflow/info"
        }
    }

def main():
    """主启动函数"""
    print("🚀 启动 CodeLintAI 服务...")
    print(f"📍 服务地址: http://{Config.HOST}:{Config.PORT}")
    print(f"📚 API文档: http://{Config.HOST}:{Config.PORT}/docs")
    print(f"🎮 Playground: http://{Config.HOST}:{Config.PORT}/langserve/commit/playground")
    print(f"🔧 调试模式: {'开启' if Config.DEBUG else '关闭'}")
    print(f"🤖 使用模型: {Config.LLM_MODEL_NAME}")
    print(f"🔍 向量模型: {Config.EMBEDDING_MODEL_NAME}")
    print(f"🔄 LangGraph工作流: 已启用")
    

    
    print("-" * 50)
    
    uvicorn.run(
        "app:app",  # 使用字符串格式，支持热部署
        host=Config.HOST, 
        port=Config.PORT,
        reload=Config.DEBUG,
        log_level="info"
    )

if __name__ == "__main__":
    main() 